package com.ex01.ylw;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * http服务器，这里主要用来接收socket并把inputStream传到Request，OutputStream传到Response
 * Created by yangliwei on 2017/7/19.
 */
public class HttpServer {
    //获取当前服务器在本机路径
    public  static final String WEB_ROOT = System.getProperty("user.dir") + File.separator;

    private boolean shutdown = false;

    private static final String FINISH = "finish";

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.start();
    }

    private void start() {
        ServerSocket serverSocket = null;
        try {
            //其中backlog是可以使用本机的端口号的数量，0代表可以使用任意数量的本机空闲端口号，1代表最多使用一个本机空闲端口号
            serverSocket = new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!shutdown) {
            Socket socket = null;
            Request request = null;
            Response response = null;
            try {
                socket = serverSocket.accept();
//                创建request和解析
                request = new Request(socket.getInputStream());
                request.parse();
//                创建response和发送
                response = new Response(socket.getOutputStream());
                response.setRequest(request);
                response.sendStaticResource();
                socket.close();

                //关闭服务器
                System.out.println(request.getUri());
                shutdown = request.getUri().equals(FINISH);

            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

        }
    }

}
